package com.ruoyi.heima.listener;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.MqConstants;
import com.ruoyi.heima.domain.po.News;
import com.ruoyi.heima.enums.NewsStatus;
import com.ruoyi.heima.service.INewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@RequiredArgsConstructor
public class SearchInitListener {

    private final INewsService newsService;

    private final RabbitTemplate rabbitTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.NEWS_INIT_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.NEWS_INIT_EXCHANGE, type = ExchangeTypes.TOPIC, durable = "true"),
            key = MqConstants.NEWS_INIT_ROUTING_KEY
    ))
    public void init() {
        int pageNo = 1;
        int pageSize = 500;

        while (true) {
            System.out.println("正在导入第 " + pageNo + " 页数据");
            Page<News> newsPage = newsService.lambdaQuery()
                    .eq(News::getStatus, NewsStatus.PUBLISH)
                    .page(new Page<>(pageNo, pageSize));

            List<News> records = newsPage.getRecords();
            for (News record : records) {
                rabbitTemplate.convertAndSend(MqConstants.NEWS_EXCHANGE, MqConstants.NEWS_ROUTING_KEY, record);
            }
            // 如果查询结果为空，则跳出循环
            if (CollectionUtils.isEmpty(records)) {
                break;
            }
            pageNo++;
        }
    }
}
